import React, {useEffect, useState} from 'react'
import {Space, Button, Modal, message} from 'antd'
import moment from 'moment'
import {history} from 'umi'
import {
	PlusOutlined,
	ArrowDownOutlined,
	ArrowUpOutlined,
} from '@ant-design/icons'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
// import Table from '@/components/Table';
import {PageType} from '../constant'
import Styles from './index.less'
import {
	getDitchList,
	getFirstChannelType,
	updateStatus,
} from '@/service/channel'
import {getAllCitys, getCompany} from '@/service/common'
import {getSubjectCompany} from '@/service/merchantCenter/clue'

import Eidtable from '../components/eidtable'
// import { getDictsByKeys } from '@/service/common/dict'
import {translateDataToTree} from '@/utils/common'
import {downloadDocumentUrl} from '@/service/common/download'
import ExportExcl from './impoart'
import Permissions from '@/components/Permissions'
import {getAllChannelType} from '@/service/merchantCenter/rewardDetails'

const statusC: any = {
	'0': '禁用',
	'1': '启用',
}

export default function List({user}: any) {
	const [formData, setFormData] = useState({})
	const [total, setTotal] = useState()
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [tableList, setTableList] = useState<any[]>([])
	const [loading, setLoading] = useState(false)
	const [visible, setVisible] = useState(false)
	const [importExcl, setImportExcl] = useState(false) // 导入弹框
	// const [form] = Form.useForm();

	const [channelTypeOneType, setChannelTypeOneType] = useState([])
	const [orgList, setOrgList] = useState([])
	const [formItem, setFormItem] = useState()
	const [secondChannelData, setSecondChannelData] = useState<any>([])

	const getChannelTypeOneType = () => {
		getFirstChannelType().then((res: any) => {
			if (res?.data?.length) {
				setChannelTypeOneType(res.data)
			}
		})
	}

	/** 获取所属公司数据 */
	const onCompany = () => {
		// eslint-disable-next-line react/destructuring-assignment
		getCompany({merchantId: user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				// setCompanyData(list as any);
				setOrgList(list)
			}
		})
	}

	useEffect(() => {
		getChannelTypeOneType()
		onCompany()
		getAllChannelType().then((res: any) => {
			if (res?.success) {
				const arr: any[] = []
				res?.data?.forEach((item: any) => {
					item?.secondChannelType.forEach((items: any) => {
						arr.push(items)
					})
				})
				setSecondChannelData(arr)
			}
		})
	}, [])

	const getTabelValue = async (value: any, pagination?: any) => {
		setLoading(true)
		let values = value
		if (values?.date) {
			values.startDate = moment(values.date[0]).format(
				'YYYY-MM-DD 00:00:00',
			)
			values.endDate = moment(values.date[1]).format(
				'YYYY-MM-DD 23:59:59',
			)
			delete values.date
		}
		setFormData(values)
		const newPagination = pagination || {
			current: 1,
			size: params.size,
		}
		setParams(newPagination)
		values = {
			...values,
			...newPagination,
			cityId: values?.cityId?.[1],
		}
		const res = await getDitchList(values)
		if (res?.data) {
			setTotal(res.data?.total || 0)
			if (res.data?.records) {
				const info = [...res.data.records]
				info.forEach((res1: any, index: number) => {
					if (
						res1.channelType === 'Zy_Channel_Type,3' ||
						res1.channelType === 'Zy_Channel_Type,4' ||
						res1.channelType === 'Zy_Channel_Type,5'
					) {
						info[index].infos = 1
					} else {
						info[index].infos = 2
					}
				})
				setTableList(info || [])
			}
		}
		setLoading(false)
	}

	const [citysList, setCitysList] = useState<any[]>([])

	const [subjectList, setSubjectList] = useState([])

	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.data) {
				setCitysList(() => res.data || [])
			}
		})
	}

	const getSubjectFun = () => {
		getSubjectCompany().then((res: any) => {
			if (res.data) {
				setSubjectList(res.data.data)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
		getSubjectFun()
		getTabelValue(formData)
	}, [])

	const onFinish = (values: any) => {
		setFormItem(values)
		getTabelValue(values)
		// eslint-disable-next-line no-param-reassign
	}

	// 搜索重置
	const onReset = () => {
		getTabelValue({})
	}

	const formItems = [
		{
			type: 'group',
			key: 'group',
			groupItems: [
				{
					type: 'input',
					label: '渠道编号',
					name: 'ditchNo',
					key: 'ditchNo',
					placeholder: '请输入',
				},
				{
					type: 'input',
					label: ' 渠道名称',
					name: 'username',
					key: 'username',
					placeholder: '请输入',
				},
				{
					type: 'select',
					label: 'AMC一级渠道类型',
					name: 'firstLevelType',
					key: 'firstLevelType',
					title: 'text',
					items: channelTypeOneType.map((item: any) => ({
						value: item.type,
						text: item.valueName,
					})),
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					label: '所属主体',
					name: 'subject',
					key: 'subject',
					title: 'text',
					items: subjectList.map((item: any) => ({
						value: item.id,
						text: item.merchantName,
					})),
				},
				{
					type: 'treeSelect',
					label: '所属公司',
					name: 'orgId',
					key: 'orgId',
					keys: 'id',
					title: 'name',
					treeData: [...orgList],
				},
				{
					type: 'select',
					label: 'AMC二级渠道类型',
					name: 'secondLevelType',
					key: 'secondLevelType',
					placeholder: '请选择',
					title: 'text',
					items: [
						{id: '1', name: '渠道sp'},
						{id: '2', name: '车司'},
						{id: '3', name: '自营-BD'},
						{id: '4', name: '自营-司推司'},
						{id: '5', name: '自营-普推司'},
					].map((item: any) => ({
						value: item.id,
						text: item.name,
					})),
				},
			],
		},
		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'select',
					label: '渠道状态',
					name: 'status',
					key: 'status',
					title: 'text',
					items: Object.keys(statusC).map((item: string) => ({
						value: item,
						text: statusC[item],
					})),
				},
				{
					type: 'input',
					label: 'sp渠道/车司负责人',
					name: 'leadingPerson',
					key: 'leadingPerson',
					placeholder: '请输入',
				},
				{
					type: 'cascader',
					label: '城市',
					name: 'cityId',
					key: 'cityId',
					placeholder: '请选择',
					items: citysList,
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
				},
			],
		},
		{
			type: 'group',
			key: 'group4',
			groupItems: [
				{
					type: 'dateRange',
					label: '创建时间',
					name: 'date',
					key: 'date',
					placeholder: '请选择',
				},
				{
					type: 'input',
					label: ' 创建人',
					name: 'createUserName',
					key: 'createUserName',
					placeholder: '请输入',
				},
				{
					type: 'input',
					label: ' 联系电话',
					name: 'phone',
					key: 'phone',
					placeholder: '请输入',
				},
			],
		},
		{
			type: 'group',
			key: 'group5',
			groupItems: [
				{
					type: 'input',
					label: '推荐人司机ID',
					name: 'driverId',
					key: 'driverId',
					placeholder: '请输入',
				},
				{},
				{},
			],
		},
	]

	const openDetail = (record: Record<string, string>) => {
		// 车司.SP跳转到供应商准入详情页面
		const text = record?.channelType?.split(',')[1]
		if (text === '1' || text === '2') {
			history.push({
				pathname: '/supplier/admittance/view',
				query: {
					id: record.supplierId,
				},
			})
		} else if (text === '3' || text === '4' || text === '5') {
			history.push({
				pathname: '/merchantCenter/channel/detail',
				query: {
					pageType: PageType.Detail,
					id: record.id,
				},
			})
		}
	}

	const openEditPage = (record: Record<string, string>) => {
		history.push({
			pathname: '/merchantCenter/channel/edit',
			query: {
				pageType: PageType.Edit,
				id: record.id,
			},
		})
	}

	const statusChange = async (record: any) => {
		const res = await updateStatus({id: record.id})
		if (res.success) {
			message.success(res.msg)
			getTabelValue(formData, params)
		} else {
			message.error(res.msg)
			getTabelValue(formData, params)
		}
	}

	const [didtableId, setDidtableId] = useState('')

	const channelColumns: any[] = [
		{title: '渠道ID', dataIndex: 'id', align: 'center', width: 250},
		{title: '渠道编号', dataIndex: 'ditchNo', align: 'center', width: 250},
		{
			title: '所属主体',
			dataIndex: 'subjectName',
			align: 'center',
			width: 150,
		},
		{title: '城市', dataIndex: 'cityName', align: 'center', width: 150},
		{title: '所属公司', dataIndex: 'orgName', align: 'center', width: 150},
		{
			title: 'AMC一级渠道类型 ',
			dataIndex: 'firstLevelType',
			align: 'center',
			width: 150,
			render: (_text: any, record: any) =>
				channelTypeOneType?.map((res: any) => {
					const text = record?.channelType?.split(',')[0]
					if (text === res?.type) {
						return <span>{res?.valueName}</span>
					}
					return ''
				}),
		},
		{
			title: 'AMC二级渠道类型',
			dataIndex: 'secondLevelType',
			align: 'center',
			width: 150,
			render: (_text: any, record: any) =>
				secondChannelData?.map((res: any) => {
					const text = record?.channelType?.split(',')[1]
					if (text === res?.value) {
						return <span>{res?.valueName}</span>
					}
					return ''
				}),
		},
		{
			title: '渠道名称',
			dataIndex: 'ditchName',
			align: 'center',
			width: 150,
		},
		{
			title: '渠道code码',
			dataIndex: 'code',
			align: 'center',
			width: 150,
			render: (text: any, record: any) => (
				<>
					{record?.channelType?.split(',')[1] !== '1' ? (
						<span>{text || '--'} </span>
					) : (
						<Button
							style={{width: '100%', overflow: 'hidden'}}
							onClick={() => {
								setVisible(true)
								setDidtableId(record.id)
							}}
							type="link">
							新增/查看
						</Button>
					)}
				</>
			),
		},

		{
			title: 'sp渠道/车司负责人',
			dataIndex: 'leadingPerson',
			align: 'center',
			width: 150,
		},
		{title: '联系电话', dataIndex: 'phone', align: 'center', width: 150},
		{
			title: '合同编码',
			dataIndex: 'contractNo',
			align: 'center',
			width: 150,
		},
		{
			title: '合同开始时间',
			dataIndex: 'contractStartDate',
			align: 'center',
			width: 150,
			render: (text: any) =>
				text ? moment(text)?.format('YYYY-MM-DD') : '',
		},
		{
			title: '合同结束时间',
			dataIndex: 'contractSettlementDate',
			align: 'center',
			width: 150,
			render: (text: any) =>
				text ? moment(text)?.format('YYYY-MM-DD') : '',
		},
		{
			title: '合同状态',
			dataIndex: 'contractStatus',
			align: 'center',
			width: 150,
		},
		{
			title: '渠道状态',
			dataIndex: 'statusName',
			align: 'center',
			width: 150,
		},
		{
			title: '结算周期',
			dataIndex: 'settlementCycle',
			align: 'center',
			width: 150,
		},
		{title: '税率', dataIndex: 'taxRate', align: 'center', width: 150},
		{
			title: '推荐人司机ID',
			dataIndex: 'driverId',
			align: 'center',
			width: 150,
			render: (text: any) => (text > 0 ? text : '-'),
		},
		{
			title: '开户银行',
			dataIndex: 'depositBank',
			align: 'center',
			width: 150,
		},
		{
			title: '开户支行',
			dataIndex: 'depositBankName',
			align: 'center',
			width: 150,
		},
		{title: '银行账号', dataIndex: 'bankCard', align: 'center', width: 150},
		{
			title: '结算方式',
			dataIndex: 'settlementMethod',
			align: 'center',
			width: 150,
		},
		{
			title: '创建人',
			dataIndex: 'createUserName',
			align: 'center',
			width: 150,
		},
		{
			title: '创建时间',
			dataIndex: 'createTime',
			align: 'center',
			width: 150,
		},
	]

	const Colunms: any[] = [
		...channelColumns,
		{
			title: '操作',
			width: 150,
			align: 'center',
			fixed: 'right',
			render: (ffield: string, record: Record<string, any>) => (
				<Space size={12}>
					<Permissions permissionID="amc_merchantCenter_channel_detail">
						<Button type="link" onClick={() => openDetail(record)}>
							详情
						</Button>
					</Permissions>
					{record?.channelType?.split(',')?.[0] ===
					'Zy_Channel_Type' ? (
						<>
							<Permissions permissionID="amc_merchantCenter_channel_edit">
								<Button
									type="link"
									onClick={() => openEditPage(record)}>
									编辑
								</Button>
							</Permissions>
							{record.status === 0 && (
								<Permissions permissionID="amc_merchantCenter_channel_operation">
									<Button
										type="link"
										onClick={() => statusChange(record)}>
										启用
									</Button>
								</Permissions>
							)}
							{record.status === 1 && (
								<Permissions permissionID="amc_merchantCenter_channel_operation">
									<Button
										type="link"
										onClick={() => statusChange(record)}>
										禁用
									</Button>
								</Permissions>
							)}
						</>
					) : (
						''
					)}
				</Space>
			),
		},
	]

	const sunChange = (value: any) => {
		if (value) {
			setImportExcl(false)
		}
	}

	return (
		<div className={Styles.list}>
			<div className={Styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '150px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={formItems}
					onFinish={onFinish}
					onReset={onReset}
				/>
			</div>
			<div className={Styles.content}>
				<div className={Styles.btnListBox}>
					<div>
						<Space size={12}>
							<Permissions permissionID="amc_merchantCenter_channel_add">
								<Button
									onClick={() => {
										history.push(
											'/merchantCenter/channel/add',
										)
									}}
									icon={<PlusOutlined />}
									type="primary"
									ghost
									size="small">
									新增
								</Button>
							</Permissions>
							<Permissions permissionID="amc_merchantCenter_channel_import">
								<Button
									icon={<ArrowUpOutlined />}
									className={Styles.warning}
									ghost
									size="small"
									onClick={() => {
										setImportExcl(true)
									}}>
									导入
								</Button>
							</Permissions>
							<Permissions permissionID="amc_merchantCenter_channel_export">
								<Button
									icon={<ArrowDownOutlined />}
									className={Styles.import}
									ghost
									size="small"
									onClick={() => {
										downloadDocumentUrl({
											resourceId: '172',
											queryDesc:
												'渠道列表导出,resourceId:172',
											queryParam: formItem,
										})
									}}>
									导出
								</Button>
							</Permissions>
						</Space>
					</div>
				</div>
				<CustomTable
					params={params}
					columns={Colunms}
					total={total}
					pagination
					scroll={{x: 1200}}
					callback={(pagination: any) => {
						getTabelValue(formData, pagination)
					}}
					loading={loading}
					dataSource={tableList}
				/>
				{/* <Table
          pagination
          params={pagination}
          columns={Colunms}
          total={total}
          callback={(pa: any) => {
            setPagination(pa);
          }}
          dataSource={[{}]}
        /> */}
			</div>
			{visible ? (
				<Modal
					title="渠道code码"
					open={visible}
					onCancel={() => {
						setVisible(false)
					}}
					width={1000}
					forceRender
					onOk={() => {
						setVisible(false)
					}}
					footer={[]}>
					<Eidtable didtableId={didtableId} />
				</Modal>
			) : (
				<></>
			)}
			<ExportExcl
				info={importExcl}
				sunchange={sunChange}
				getData={getTabelValue}
			/>
		</div>
	)
}
